using System;
using System.Collections.Generic;
using Autofac;
using UnityEngine;

namespace AuthorLifeEditor
{
    public static class AutofacConfiguration
    {
        /// <summary>
        /// 从内存中解析json， 并注册模块
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="json"></param>
        public static void RegisterModulesFromJson(this ContainerBuilder builder, string json)
        {
            var autofacConfig = JsonUtility.FromJson<AutofacConfig>(json);
            var modules = autofacConfig.modules;
            foreach (var module in modules)
            {
                var moduleType = Type.GetType(module.type);
                if (moduleType == null)
                    throw new Exception($"没找到模块：{module.type}, 请检查配置文件是否配置正确");
                
                builder.RegisterAssemblyModules(moduleType, AppDomain.CurrentDomain.GetAssemblies());
            }
        }
        
        /// <summary>
        /// 从绝对路径的文件里加载json文件，并解析注册模块
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="path"></param>
        public static void RegisterModulesFromFile(this ContainerBuilder builder, string path)
        {
            var json = System.IO.File.ReadAllText(path);
            RegisterModulesFromJson(builder, json);
        }
        
        /// <summary>
        /// 从Resources目录里加载json文件，并解析注册模块
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="path"></param>
        public static void RegisterModulesFromResources(this ContainerBuilder builder, string path)
        {
            var textAsset = Resources.Load<TextAsset>(path);
            RegisterModulesFromJson(builder, textAsset.text);
        }
    }
    
    [Serializable]
    public class Module
    {
        public string type;
    }

    [Serializable]
    public class AutofacConfig
    {
        public string defaultAssembly;
        public List<Module> modules;
    }
}